//
//  TSAuthenticationViewController.swift
//  TopStock
//
//  Created by dyd on 2017/8/8.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit

class TSAuthenticationViewController: UIViewController {
    @IBOutlet weak var checkButton: UIButton!
    
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        checkButton.backgroundColor = BtnTimingBackColor
        checkButton.isEnabled = false
        self.remainingSeconds = 5
        self.isCommence = !self.isCommence

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func backItemAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func checkButtonAction(_ sender: UIButton){
        self.dismiss(animated: true, completion: nil)
    }
    
    //倒计时的时间计算器
    private var isCommence: Bool = false {//是否开始计时
        willSet(newValue) {
            if newValue {
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
            } else {
                timer?.invalidate()
                timer = nil
            }
        }
    }
    
    //倒计时数
    private var remainingSeconds: Int = 0 {//remainingSeconds数值改变时 江将会调用willSet方法
        willSet(newSeconds) {
            let seconds = newSeconds%60
            checkButton.setTitle(NSString(format: "%ds", seconds) as String, for: .normal)
        }
    }
    
    // 更新时间
    func updateTimer(timer: Timer) {
        if remainingSeconds > 0 {
            remainingSeconds -= 1
        }
        if remainingSeconds == 0 {
            checkButton.setTitle("确认", for: .normal)
            checkButton.isEnabled = true
            checkButton.backgroundColor = BtnBackColor
            isCommence = !isCommence
            timer.invalidate()
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
